package com.neudu.glsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neudu.glsb.pojo.AdminUsers;
import com.neudu.glsb.pojo.Employees;
import com.neudu.glsb.service.AdminUsersService;
import com.neudu.glsb.mapper.AdminUsersMapper;
import com.neudu.glsb.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author Lenovo
 * @description 针对表【admin_users(管理员用户信息)】的数据库操作Service实现
 * @createDate 2025-04-16 22:28:32
 */
@Transactional
@Service
public class AdminUsersServiceImpl extends ServiceImpl<AdminUsersMapper, AdminUsers>
    implements AdminUsersService{

    @Autowired
    private EmployeesService employeesService;
    @Autowired
    private AdminUsersMapper adminUsersMapper;

    @Override
    public List<Map<String, Object>> getAllAccounts() {
        return adminUsersMapper.getAllAccounts();
    }

    public boolean assignAccount(Map<String, Object> accountInfo) {
        // 创建新账号
        AdminUsers newAccount = new AdminUsers();
        newAccount.setUsername((String) accountInfo.get("username"));
        newAccount.setPassword((String) accountInfo.get("password"));
        newAccount.setEmail((String) accountInfo.get("email"));
        newAccount.setRoleId((Integer) accountInfo.get("role_id"));
        newAccount.setEmployeeId((Integer) accountInfo.get("employeeId"));
        LambdaQueryWrapper<AdminUsers> query = new LambdaQueryWrapper<>();
        query.eq(AdminUsers::getUsername, accountInfo.get("username"));
        if (this.count(query) > 0) {
            throw new RuntimeException("用户名已存在");
        }
        LambdaQueryWrapper<AdminUsers> emailQuery = new LambdaQueryWrapper<>();
        emailQuery.eq(AdminUsers::getEmail, accountInfo.get("email"));
        if (this.count(emailQuery) > 0) {
            throw new RuntimeException("邮箱已存在");
        }
        // 保存账号并获取自增ID
        if (!this.save(newAccount)) return false;

        // 更新员工表关联
        UpdateWrapper<Employees> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("admin_user_id", newAccount.getId())
                .eq("id", accountInfo.get("employeeId"));
        return employeesService.update(updateWrapper);
    }
}




